<template>
  <div class="app-container">
    <div v-show="!modifyInfo.visible && !detailInfo.visible">
      <!-- 条件栏 -->
      <page-filter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.list"
      >
        <template v-slot:filter-delete>
          <el-button :disabled="!canDelete" @click="delByIds()">删除</el-button>
        </template>
        <template v-slot:filter-upload>
          <el-upload
            :headers="uploadInfo.headers"
            :show-file-list="false"
            :on-error="uploadError"
            :on-success="uploadSuccess"
            :before-upload="beforeUpload"
            :action="uploadInfo.action"
          >
            <el-button>导入产品</el-button>
          </el-upload>
        </template>
      </page-filter>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="getDepotProductPage"
        :tab-index="true"
        :check-box="true"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-depotName="scope">
          <span
            v-if="$permission('depotProduct:detail')"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.depotName }}</span
          >
          <span v-else class="slip-edit">{{ scope.row.depotName }}</span>
        </template>
      </table-container>
    </div>
    <Modify
      v-if="modifyInfo.visible"
      :id="modifyInfo.id"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      @returnModify="getList"
    />
    <Details
      v-if="detailInfo.visible"
      :id="detailInfo.id"
      v-model:visible="detailInfo.visible"
    ></Details>
  </div>
</template>

<script setup name="depotProduct">
import {
  depotProductDisabled,
  depotProductEnabled,
  depotProductDel,
  getDepotProductPage,
} from '@/api/core.js'
import Modify from './modify'
import Details from './details'
import { getDepotAll } from '@/api/core'
import { ElLoading } from 'element-plus'
import { exportTemplateExcel } from '@/api/pub'

const { proxy } = getCurrentInstance()

const uploadInfo = ref({
  action: import.meta.env.VITE_APP_BASE_API + '/core/depotProduct/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    searchType: 'depot',
    sort: 'create_time desc',
    depotAuth: 'depotId',
  },
  list: [
    {
      type: 'button',
      label: '新增',
      event: add,
      show: proxy.$permission('depotProduct:add'),
    },
    {
      type: 'slot',
      label: '删除',
      value: 'delete',
      show: proxy.$permission('depotProduct:delete'),
    },
    {
      type: 'button',
      label: '下载模板',
      event: downloadTemplate,
      show: proxy.$permission('depotProduct:downloadTemplate'),
    },
    {
      type: 'slot',
      value: 'upload',
      show: proxy.$permission('depotProduct:upload'),
    },
    {
      label: '仓库',
      value: 'depotIdMult',
      type: 'slip-select',
      query: {
        depotAuth: 'id',
        status: 1,
      },
      api: getDepotAll,
      clearable: true,
      filterable: true,
      multiple: true,
      event: search,
    },
    {
      label: '状态',
      value: 'status',
      type: 'select-model',
      code: 'enabled_type',
      event: search,
      clearable: true,
    },
    {
      label: '是否以领定消',
      value: 'isReceiveConsume',
      type: 'select-model',
      code: 'yes_or_no',
      event: search,
      clearable: true,
    },
    { type: 'button', label: '搜索', event: search },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  selections: [],
  data: [],
  fieldList: [
    { label: '仓库名称', value: 'depotName', type: 'slot' },
    { label: '仓库编码', value: 'depotCode' },
    { label: '状态', value: 'statusValue' },
    { label: '是否以领定消', value: 'isReceiveConsumeValue' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('depotProduct:update'),
      },
      {
        label: '启用',
        event: enabled,
        show: proxy.$permission('depotProduct:enabled'),
        ifRender: function (row) {
          return row.status === 0
        },
      },
      {
        label: '停用',
        event: disabled,
        show: proxy.$permission('depotProduct:disabled'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '删除',
        event: delByIds,
        show: proxy.$permission('depotProduct:delete'),
        ifRender: function (row) {
          return row.status === 0
        },
      },
    ],
  },
})
//明细相关
const modifyInfo = ref({
  visible: false,
  title: '仓库产品明细',
  id: '',
})
const detailInfo = ref({
  visible: false,
  id: '',
})
const tableRow = ref('')

const canDelete = computed(() => {
  return (
    tableInfo.value.selections.length &&
    //后台状态值都是数字
    tableInfo.value.selections.filter((row) => row.status !== 0).length === 0
  )
})

onMounted(() => {
  getList()
})

function delByIds(row) {
  //删除
  proxy
    .$confirm('删除后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      const ids = getIds(row)
      depotProductDel(ids).then((resp) => {
        if (resp) {
          getList()
        }
      })
    })
}
function enabled(row) {
  //启用
  const ids = getIds(row)
  depotProductEnabled(ids).then((resp) => {
    if (resp) {
      getList()
    }
  })
}
function disabled(row) {
  //停用
  const ids = getIds(row)
  depotProductDisabled(ids).then((resp) => {
    if (resp) {
      getList()
    }
  })
}
function getIds(row) {
  if (row) {
    return [row.id]
  } else {
    return tableInfo.value.selections.map((value) => value.id)
  }
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = data
      break
  }
}
function add() {
  modifyInfo.value.id = ''
  modifyInfo.value.visible = true
}
function update(row) {
  sessionStorage.setItem('storeRowId', row.id)
  modifyInfo.value.id = row.id
  modifyInfo.value.visible = true
}
function beforeUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some(
    (type) => file.name.split('.')[file.name.split('.').length - 1] === type
  )
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  return isFileType && isLt
}
function uploadSuccess(resp) {
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    proxy.$message.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    getList()
  } else {
    proxy.$message.error({
      message: resp.msg,
      duration: 0,
      showClose: true,
    })
  }
}
function uploadError(err) {
  if (err) {
    proxy.$message.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.value.id = row.id
  detailInfo.value.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function downloadTemplate() {
  exportTemplateExcel('depot_product').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
</script>

<style scoped></style>
